package ru.nsu.fit.ask_joe.user_interface_manager.realization;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import ru.nsu.fit.ask_joe.MainManager;
import ru.nsu.fit.ask_joe.R;
import ru.nsu.fit.ask_joe.user_interface_manager.interfaces.IPanel;
import ru.nsu.fit.client.core.response.*;

import java.util.ArrayList;

public class MyQuestionPanel implements IPanel {
	
	private static final int resourceId = R.layout.my_questions;
	
	private final View _view;
	private final Button _buttonOtherQuest, _buttonMyProfile, _buttonAskJoe, _buttonBack, _buttonNext;
    private int currentQuestion = 0;
    private QuestionStatData questions = null;
    private ArrayList<TextView> _answerTexts = new ArrayList<TextView>();
    private ArrayList<ProgressBar> _answerBars = new ArrayList<ProgressBar>();
    private ArrayList<TextView> _answerPercents = new ArrayList<TextView>();
    private final TextView _textTime, _textTitle;
    private ProgressDialog _progressDialog;

    private class ResponseProcessor extends KernelResponseProcessor
    {
        @Override
        protected void onPostExecute(KernelResponse result) {
            super.onPostExecute(result);
            if (result.isSuccessful() && result.getData() != null)
            {
                if (result.getData() instanceof UserStatisticsData)
                {
                    MainManager.getUserInterfaceManager().setStatistics((UserStatisticsData) result.getData());
                    currentQuestion = 0;
                    loadQuestion();
                }
                else if (result.getData() instanceof QuestionStatData)
                {
                    questions = (QuestionStatData)result.getData();
                    loadQuestion();
                }
            }
            else
            {
                if (_progressDialog != null)
                {
                    _progressDialog.dismiss();
                    _progressDialog = null;
                }

                AlertDialog.Builder builder =  new AlertDialog.Builder(getView().getContext());
                builder.setTitle(getView().getContext().getString(R.string.Message_Error));
                builder.setMessage(result.getErrorText()); //TODO translate error message into current language
                builder.setPositiveButton(getView().getContext().getString(R.string.Button_Ok), null);
                builder.show();

                MainManager.getLogManager().getLogger().printError("Cannot get my questions. Result = " + result.getErrorText());
            }
        }
    }
	
	public MyQuestionPanel()
	{
		_view = MainManager.getUserInterfaceManager().getMainActivity().getLayoutInflater().inflate(resourceId, null);
		
		_buttonOtherQuest = (Button)_view.findViewById(R.id.button_other_quest);
		_buttonOtherQuest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MainManager.getUserInterfaceManager().setCurrentPanel(new OtherQuestionPanel());
			}
		});
		
		_buttonMyProfile = (Button)_view.findViewById(R.id.button_my_profile);
		_buttonMyProfile.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MainManager.getUserInterfaceManager().setCurrentPanel(new ProfilePanel());
			}
		});
		
		_buttonAskJoe = (Button)_view.findViewById(R.id.button_ask_joe);
		_buttonAskJoe.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MainManager.getUserInterfaceManager().setCurrentPanel(new AskJoePanel());
			}
		});
		
		_buttonBack = (Button)_view.findViewById(R.id.button_back);
        _buttonBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                _buttonBack.setEnabled(false);
                _buttonNext.setEnabled(false);
                currentQuestion--;
                showQuestion();
            }
        });
		_buttonNext = (Button)_view.findViewById(R.id.button_next);
        _buttonNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                _buttonBack.setEnabled(false);
                _buttonNext.setEnabled(false);
                currentQuestion++;
                showQuestion();
            }
        });

        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer1));
        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer2));
        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer3));
        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer4));
        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer5));
        _answerTexts.add((TextView) _view.findViewById(R.id.text_answer6));

        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer1));
        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer2));
        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer3));
        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer4));
        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer5));
        _answerBars.add((ProgressBar) _view.findViewById(R.id.progress_answer6));

        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent1));
        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent2));
        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent3));
        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent4));
        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent5));
        _answerPercents.add((TextView) _view.findViewById(R.id.text_percent6));

        _textTime = (TextView) _view.findViewById(R.id.textView3);
        _textTitle = (TextView) _view.findViewById(R.id.text_question);

        loadQuestion();
	}
	
	private void loadQuestion()
	{
        _buttonBack.setEnabled(false);
        _buttonNext.setEnabled(false);

        UserStatisticsData statistics = MainManager.getUserInterfaceManager().getStatistics();
        if (statistics == null)
        {
            if (_progressDialog == null)
                _progressDialog = ProgressDialog.show(_view.getContext(), _view.getContext().getString(R.string.Message_PleaseWait), _view.getContext().getString(R.string.Message_LoadingQuestions));

            questions = null;
            int responseId = MainManager.getClientKernel().getUserStatistics();
            new ResponseProcessor().execute(responseId);
        }
        else if (questions == null && statistics.getMyQuestions().size() > 0)
        {
            if (_progressDialog == null)
                _progressDialog = ProgressDialog.show(_view.getContext(), _view.getContext().getString(R.string.Message_PleaseWait), _view.getContext().getString(R.string.Message_LoadingQuestions));

            int responseId = MainManager.getClientKernel().getQuestionsStats(statistics.getMyQuestions());
            new ResponseProcessor().execute(responseId);
        }
        else
        {
            if (_progressDialog != null)
            {
                _progressDialog.dismiss();
                _progressDialog = null;
            }

            currentQuestion = 0;
            showQuestion();
        }
	}

    private void showQuestion()
    {
        if (questions == null || questions.getQuestions().size() == 0)
        {
            return;
        }

        if (currentQuestion > 0)
        {
            _buttonBack.setEnabled(true);
        }
        if (currentQuestion < MainManager.getUserInterfaceManager().getStatistics().getMyQuestions().size() - 1)
        {
            _buttonNext.setEnabled(true);
        }


        //TODO show question in gui
        QuestionStat question = questions.getQuestions().get(questions.getQuestions().size() - currentQuestion - 1);

        _textTitle.setText(question.getText());
        long lifetime = question.getLifetime() / 1000;
        String lifetimeStr = String.format("%dm:%ds", (lifetime / 60) % 60, lifetime % 60);
        if (lifetime >= 60 * 60)
        {
            lifetimeStr = String.format("%dh:%s", lifetime / 3600, lifetimeStr);
        }
        _textTime.setText(lifetimeStr);
        int totalHits = 0;
        for (Integer i : question.getAnswerHits())
        {
            totalHits += i;
        }

        for (int i = 0; i < _answerBars.size(); ++i)
        {
            if (i < question.getAnswers().size())
            {
                _answerTexts.get(i).setText(question.getAnswers().get(i));
                _answerBars.get(i).setMax(totalHits == 0 ? 1 : totalHits);
                _answerBars.get(i).setProgress(question.getAnswerHits().get(i));
                _answerPercents.get(i).setText(String.valueOf(question.getAnswerHits().get(i)));

                _answerTexts.get(i).setVisibility(View.VISIBLE);
                _answerBars.get(i).setVisibility(View.VISIBLE);
                _answerPercents.get(i).setVisibility(View.VISIBLE);
            }
            else
            {
                _answerTexts.get(i).setVisibility(View.INVISIBLE);
                _answerBars.get(i).setVisibility(View.INVISIBLE);
                _answerPercents.get(i).setVisibility(View.INVISIBLE);
            }
        }
    }
	
	@Override
	public View getView() {
		return _view;
	}
}
